/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package com.googlecode.ivybeans.facade;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.ivy.Ivy;
import org.apache.ivy.core.module.descriptor.ModuleDescriptor;
import org.apache.ivy.core.module.id.ModuleRevisionId;
import org.apache.ivy.core.report.ArtifactDownloadReport;
import org.apache.ivy.core.report.ResolveReport;
import org.apache.ivy.core.resolve.IvyNode;

/**
 * A library of artifacts (usually jars) resolved by Ivy, available on the file system.
 * 
 * @see IvyLibrary
 */
public class ResolvedIvyLibrary {
    public static final ResolvedIvyLibrary EMPTY_RESOLVED = new ResolvedIvyLibrary();

    private ResolveReport report;

    private Ivy ivy;

    private ResolvedIvyLibrary() {
    }
    
    ResolvedIvyLibrary(Ivy ivy, ResolveReport report) {
        this.ivy = ivy;
        this.report = report;
    }

    /**
     * Returns the list of main artifacts which are part of this library, as a List of ArtifactInfo.
     * The returned list is never <code>null</code>, but may be empty.
     * 
     * @return the list of main artifacts which are part of this library, as a List of ArtifactInfo.
     */
    public Collection<ArtifactInfo> getArtifacts() {
        if (report == null) {
            return Collections.emptyList();
        }
        List<ArtifactInfo> artifacts = new ArrayList<ArtifactInfo>();
        ArtifactDownloadReport[] reports = report.getAllArtifactsReports();
        for (int i = 0; i < reports.length; i++) {
            
            if (reports[i].getLocalFile() != null 
                    && "jar".equals(reports[i].getType())) {
                ModuleDescriptor md = getDescriptor(
                        report, reports[i].getArtifact().getModuleRevisionId());
                artifacts.add(new ArtifactInfo(ivy, md, reports[i]));
            }
        }
        return artifacts;
    }

    private ModuleDescriptor getDescriptor(ResolveReport report, ModuleRevisionId moduleRevisionId) {
        for (Iterator it = report.getDependencies().iterator(); it.hasNext();) {
            IvyNode node = (IvyNode)it.next();
            if (node.getId().equals(moduleRevisionId)) {
                return node.getDescriptor();
            }
        }
        return null;
    }
}

